package com.ajun.notice;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

@Slf4j
public class FeishuSignUtil {

    public static final String ENCODE_TYPE_HMAC_SHA_256 = "HmacSHA256";
    public static final String ENCODE_UTF_8_LOWER = "utf-8";
    public static final String ENCODE_UTF_8_UPPER = "UTF-8";

    public static String getSHA256Str(String secretKey, String toSignStr) throws Exception {
        if (StrUtil.isEmpty(secretKey)) {
            return null;
        }
        String encodeStr = null;
        //HMAC_SHA256 加密
        Mac hmac_sha256 = Mac.getInstance(ENCODE_TYPE_HMAC_SHA_256);
        SecretKeySpec secre_spec = new SecretKeySpec(toSignStr.getBytes(),
                ENCODE_TYPE_HMAC_SHA_256);
        hmac_sha256.init(secre_spec);
        byte[] bytes = hmac_sha256.doFinal();
        if (null == bytes || bytes.length < 1) {
            return null;
        }

        String base64 = Base64.encodeBase64String(bytes);
        if (StrUtil.isEmpty(base64)) {
            return null;
        }
        encodeStr = base64;
        return encodeStr;
    }


    public static String getSignStr(String feiShuSecretKey, long timestamp) throws Exception {
        String toSign = timestamp + "\n" + feiShuSecretKey;
        return getSHA256Str(feiShuSecretKey, toSign);
    }
}
